package com.itheima.template;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import com.aliyun.teaopenapi.models.Config;
import com.itheima.properties.SmsProperties;

//短信对象类
//模块创建模板对象发送信息
public class SmsTemplate {
    //调用 短信属性 对象
    private SmsProperties smsProperties;

    //短信模板
    public SmsTemplate(SmsProperties smsProperties) {
        this.smsProperties = smsProperties;
    }

    /**
     * 发送验证码短信
     *
     * @param mobile
     * @param code
     */
    public void sendSms(String mobile,String code){
        try {
            //配置阿里云
            Config config = new Config()
                    // 您的AccessKey ID
                    .setAccessKeyId(smsProperties.getAccessKey())
                    // 您的AccessKey Secret
                    .setAccessKeySecret(smsProperties.getSecret());

            //配置访问的域名
            config.endpoint = "dysmsapi.aliyuncs.com";
            //创建用户对象 赋值加解密。
            //注意阿里云包
            Client client=new Client(config);

            //发送短信请求对象
            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    //写入电话
                    .setPhoneNumbers(mobile)
                    //写入签名名称 通过短信属性对象获得
                    .setSignName(smsProperties.getSignName())
                    //写入短信模板id
                    .setTemplateCode(smsProperties.getTemplateCode())
                    //写入验证码
                    .setTemplateParam("{\"code\":\"" + code + "\"}");

            //复制代码运行请自行打印 API 的返回值
            SendSmsResponse response = client.sendSms(sendSmsRequest);
            if ("OK".equals(response.getBody().getCode())) {
                System.out.println("验证码发送成功");
            }
            SendSmsResponseBody body = response.getBody();

            System.out.println(body.getMessage());


        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
